import { Ref, ref } from "vue";

export default function useDialog<T = any>(options?: any) {
  const visible = ref(options?.default ?? false);
  const source = ref<T>();

  const events = {
    open,
    close,
    onOpen: open,
    onClose: close,
  };

  function close() {
    visible.value = false;
    Promise.resolve().then(() => {
      source.value = undefined;
    });
  }

  function open(payload?: any) {
    source.value = payload;
    visible.value = true;
  }

  return [
    visible,
    {
      ...events,
      source,
    },
  ] as [
    Ref<boolean>,
    {
      source: Ref<T>;
      open: typeof open;
      close: typeof open;
    }
  ];
}
